<?php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

// Require login to access checkout
requireLogin();

$user_id = $_SESSION['user_id'];
$cart_items = getCartItems($pdo, $user_id);
$cart_total = getCartTotal($pdo, $user_id);

// Redirect if cart is empty
if (empty($cart_items)) {
    header('Location: index.php');
    exit();
}

$error_message = '';
$success_message = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $shipping_address = sanitizeInput($_POST['shipping_address']);
    $billing_address = sanitizeInput($_POST['billing_address']);
    $payment_method = sanitizeInput($_POST['payment_method']);
    $notes = sanitizeInput($_POST['notes']);
    
    if (empty($shipping_address) || empty($billing_address) || empty($payment_method)) {
        $error_message = 'Please fill in all required fields.';
    } else {
        try {
            $shipping_cost = $cart_total >= 100 ? 0 : 10;
            $total_amount = $cart_total + $shipping_cost;
            
            $order_data = [
                'total_amount' => $total_amount,
                'shipping_address' => $shipping_address,
                'billing_address' => $billing_address,
                'payment_method' => $payment_method,
                'notes' => $notes
            ];
            
            $order_id = createOrder($pdo, $user_id, $order_data);
            
            if ($order_id) {
                // Redirect immediately to success page instead of using refresh
                header('Location: /chuan/535g/user/orders.php?order_success=1&order_id=' . $order_id);
                exit();
            } else {
                $error_message = 'Error placing order. Please try again.';
            }
        } catch (Exception $e) {
            $error_message = 'Error placing order: ' . $e->getMessage();
        }
    }
}

$page_title = "Checkout";
?>
<?php include '../includes/header.php'; ?>

<main style="padding: 2rem 0;">
    <div class="container">
        <h1 style="margin-bottom: 2rem; color: #2c3e50;">Checkout</h1>

        <?php if ($success_message): ?>
            <div class="alert alert-success"><?php echo $success_message; ?></div>
        <?php endif; ?>

        <?php if ($error_message): ?>
            <div class="alert alert-error"><?php echo $error_message; ?></div>
        <?php endif; ?>

        <form method="POST" action="">
            <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 2rem;">
                <!-- Checkout Form -->
                <div>
                    <div class="card">
                        <div class="card-header">
                            <h2>Shipping Information</h2>
                        </div>
                        
                        <div class="form-group">
                            <label for="shipping_address">Shipping Address *</label>
                            <textarea id="shipping_address" name="shipping_address" rows="4" required 
                                      placeholder="Enter your complete shipping address"><?php echo isset($_POST['shipping_address']) ? htmlspecialchars($_POST['shipping_address']) : ''; ?></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label for="billing_address">Billing Address *</label>
                            <textarea id="billing_address" name="billing_address" rows="4" required 
                                      placeholder="Enter your billing address"><?php echo isset($_POST['billing_address']) ? htmlspecialchars($_POST['billing_address']) : ''; ?></textarea>
                        </div>
                    </div>

                    <div class="card">
                        <div class="card-header">
                            <h2>Payment Information</h2>
                        </div>
                        
                        <div class="form-group">
                            <label for="payment_method">Payment Method *</label>
                            <select id="payment_method" name="payment_method" required>
                                <option value="">Select payment method</option>
                                <option value="credit_card" <?php echo (isset($_POST['payment_method']) && $_POST['payment_method'] === 'credit_card') ? 'selected' : ''; ?>>Credit Card</option>
                                <option value="debit_card" <?php echo (isset($_POST['payment_method']) && $_POST['payment_method'] === 'debit_card') ? 'selected' : ''; ?>>Debit Card</option>
                                <option value="paypal" <?php echo (isset($_POST['payment_method']) && $_POST['payment_method'] === 'paypal') ? 'selected' : ''; ?>>PayPal</option>
                                <option value="bank_transfer" <?php echo (isset($_POST['payment_method']) && $_POST['payment_method'] === 'bank_transfer') ? 'selected' : ''; ?>>Bank Transfer</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label for="notes">Order Notes (Optional)</label>
                            <textarea id="notes" name="notes" rows="3" 
                                      placeholder="Any special instructions for your order"><?php echo isset($_POST['notes']) ? htmlspecialchars($_POST['notes']) : ''; ?></textarea>
                        </div>
                    </div>
                </div>

                <!-- Order Summary -->
                <div>
                    <div class="card">
                        <div class="card-header">
                            <h2>Order Summary</h2>
                        </div>
                        
                        <!-- Order Items -->
                        <div style="margin-bottom: 1.5rem;">
                            <?php foreach ($cart_items as $item): ?>
                                <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.5rem 0; border-bottom: 1px solid #ecf0f1;">
                                    <div>
                                        <div style="font-weight: 500;"><?php echo htmlspecialchars($item['name']); ?></div>
                                        <div style="color: #7f8c8d; font-size: 0.9rem;">Qty: <?php echo $item['quantity']; ?></div>
                                    </div>
                                    <div><?php echo formatPrice($item['price'] * $item['quantity']); ?></div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        
                        <!-- Totals -->
                        <div style="margin-bottom: 1.5rem;">
                            <div style="display: flex; justify-content: space-between; margin-bottom: 0.5rem;">
                                <span>Subtotal:</span>
                                <span><?php echo formatPrice($cart_total); ?></span>
                            </div>
                            <div style="display: flex; justify-content: space-between; margin-bottom: 0.5rem;">
                                <span>Shipping:</span>
                                <span><?php echo $cart_total >= 100 ? 'FREE' : '$10.00'; ?></span>
                            </div>
                            <div style="display: flex; justify-content: space-between; font-weight: bold; font-size: 1.1rem; border-top: 1px solid #ecf0f1; padding-top: 0.5rem;">
                                <span>Total:</span>
                                <span><?php echo formatPrice($cart_total + ($cart_total >= 100 ? 0 : 10)); ?></span>
                            </div>
                        </div>

                        <button type="submit" class="btn btn-primary" style="width: 100%; margin-bottom: 1rem;">
                            <i class="fas fa-credit-card"></i> Place Order
                        </button>
                        
                        <a href="index.php" class="btn btn-outline" style="width: 100%; text-align: center;">
                            <i class="fas fa-arrow-left"></i> Back to Cart
                        </a>
                    </div>

                    <!-- Security Notice -->
                    <div class="card" style="margin-top: 1rem;">
                        <h3 style="margin-bottom: 1rem; color: #2c3e50;">Secure Checkout</h3>
                        <div style="color: #7f8c8d; font-size: 0.9rem; line-height: 1.5;">
                            <p>Your payment information is secure and encrypted. We use industry-standard security measures to protect your data.</p>
                            <p style="margin-top: 0.5rem;"><strong>Note:</strong> This is a demo site. No real payments will be processed.</p>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</main>

<?php include '../includes/footer.php'; ?>
